<template>
  <div class="dept-allot-content">
    <div class="dept-header-btn" v-if="getTrialStatus == '1'">
      <el-button type="primary" plain icon="el-icon-plus" @click="handleDeptMenu(0)"
        >增加研究者及机构</el-button
      >
<!--      <el-button type="primary" plain icon="el-icon-search" @click="handleDeptMenu(1)"
        >分配结果</el-button
      >-->
      <el-button type="primary" plain icon="el-icon-plus" @click="handleDeptMenu(2)"
        >增加病例量</el-button
      >
    </div>
    <div style="color: black; font-size: 14px; font-weight: 550; margin-bottom: 10px">
      预计病例总量：{{ groupCaseSum || 0 }}
    </div>
    <div class="case-content">
      <div class="group-case-content">
        <div class="group-case-header">各分组病例量</div>
        <div
          class="group-case-list"
          v-for="(item, index) in groupCaseList"
          :key="index"
          @click="handleDeptMenu(3, item)"
        >
          <div class="group-case-label">{{ item.name }}</div>
          <div class="group-case-value">{{ item.caseNum }}</div>
        </div>
        <div class="group-case-list" style="color: red">
          <div class="group-case-label">总 计</div>
          <div class="group-case-value">{{ groupCaseSum || 0 }}</div>
        </div>
      </div>
      <div class="group-case-content">
        <div class="group-case-header">各中心病例量</div>
        <div
          class="group-case-list"
          v-for="(item, index) in centreCaseList"
          :key="index"
          @click="handleDeptMenu(4, item)"
        >
          <div class="group-case-label">{{ item.hospitalDeptName }}</div>
          <div class="group-case-value">{{ item.caseNum }}</div>
        </div>
        <div class="group-case-list" style="color: red">
          <div class="group-case-label">总 计</div>
          <div class="group-case-value">{{ centreCaseSum || 0 }}</div>
        </div>
      </div>
    </div>
    <el-dialog v-model="isDeptAllot" :title="deptAllotDialogTitle" :width="deptAllotDialogWidth">
      <avue-form :option="deptAllotOption" v-model="deptAllotForm" @submit="deptAllSubmit">
        <template #TJRL="{}" v-if="deptMenuType === 2 || deptMenuType === 3 || deptMenuType === 4">
          <el-input v-model="deptAllotForm.TJRL" placeholder="">
            <template #append>
              <el-button @click="handleApplyAll">应用全部</el-button>
            </template>
          </el-input>
        </template>
        <template
          #groupList="{}"
          v-if="deptMenuType === 2 || deptMenuType === 3 || deptMenuType === 4"
        >
          <div
            v-for="item in deptAllotForm.groupNumInfo"
            :key="item.id"
            style="display: flex; align-items: center; margin-bottom: 18px"
          >
            <span style="width: 160px; text-align: center">{{ item.name }}</span>
            <el-input
              v-model="item.num"
              placeholder="请输入数量"
              @input="handleInput(item)"
            ></el-input>
          </div>
        </template>
      </avue-form>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, computed, onMounted, defineEmits } from 'vue';
import {
  hospitalCaseNumOfTrial,
  groupListOfTrial,
  hospitalCaseNumSubmit,
  hospitalCaseNumDetail,
  getDetail,
  getTrialDetail,
} from '@/api/trial/trial';
import { deptOfTrial, addGroupCaseNum } from '@/api/group/group';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useStore } from 'vuex';
import caseloadOptions from '@/option/caseload/caseload';
import deptAllot from '@/option/deptAllot/deptAllot';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const emit = defineEmits();
const routerQuery = ref({});
routerQuery.value = route.query;
const router = useRouter();
const store = useStore();
const userInfo = computed(() => store.getters.userInfo);
let groupCaseList = ref([]);
let centreCaseList = ref([]);
let groupCaseSum = ref(0);
let centreCaseSum = ref(0);
let deptMenuType = ref(null);
let isDeptAllot = ref(false);
let deptAllotDialogWidth = ref(500);
let deptAllotDialogTitle = ref('');
let deptAllotOption = ref({});
let deptAllotForm = ref({});
let sendDeptAllot = ref(deptAllot);
let sendCaseloadOptions = ref(caseloadOptions);

let getTrialStatus = ref('2');

/*
  type 0:增加研究者及机构
  type 1:分配结果
  type 2:增加病例量
  type 3:各分组病例量
  type 4:各中心病例量
*/
const handleDeptMenu = (type, item = {}) => {
  if (getTrialStatus.value != '1') return;
  deptMenuType.value = type;
  for (const key in deptAllotForm.value) {
    deptAllotForm.value[key] = '';
  }
  const actions = {
    0: () => {
      isDeptAllot.value = true;
      deptAllotDialogTitle.value = '增加研究者及机构';
      deptAllotOption.value = sendDeptAllot.value;
      // 申办人字段（暂时）
      deptAllotForm.value.createUser = userInfo.value.userId;
      // 负责人字段（暂时）
      deptAllotForm.value.FZR = userInfo.value.userId;
      initCaseData(type);
    },
    1: () => {
      router.push({
        path: '/trial/allocation',
        query: {
          selectTab: 3,
          trialId: routerQuery.value.trialId,
        },
      });
    },
    2: () => {
      initCase(type);
      initCaseData(type);
    },
    3: () => {
      initCase(type, item);
      initCaseData(type);
    },
    4: () => {
      initCase(type, item);
      initCaseData(type);
    },
  };

  // 执行对应的操作
  if (actions[type]) actions[type]();
};
const initCase = (type, item = {}) => {
  isDeptAllot.value = true;
  deptAllotDialogTitle.value = '增加病例量';
  deptAllotOption.value = sendCaseloadOptions.value;
};
import { findObject } from '@smallwei/avue';
const initCaseData = (type, item = {}) => {
  deptAllotForm.value.groupNumInfo = [];
  deptOfTrial(routerQuery.value.trialId).then(res => {
    let DATA = res.data.data;
    deptAllotForm.value.hospitalDeptName = DATA.map(ele => ele.deptName).join(',');
    deptAllotForm.value.hospitalDept = DATA.map(ele => ele.id).join(',');
    const column = findObject(deptAllotOption.value.column, 'dept');
    column.dicData = DATA;
  });
  // 业务管理detail接口
  if (routerQuery.value.trialId) {
    getDetail(routerQuery.value.trialId).then(res => {
      // 业务名称字段（暂时）
      deptAllotForm.value.YWMC = res.data.data.name;
      // 主要研究者（录入员）字段（暂时）
      deptAllotForm.value.YJZ = res.data.data.researcher;
    });
  }
  groupCaseList.value.forEach(item => {
    deptAllotForm.value.groupNumInfo.push({
      groupId: item.id,
      num: 0,
      name: item.name,
    });
  });
};
const initDetail = id => {
  hospitalCaseNumDetail(id).then(res => {
    let DATA = res.data.data;
    deptAllotForm.value = DATA;
  });
};
const handleInput = item => {
  // let sum = sumValues(caseloadForm.value.groupNumInfo);
  // caseloadForm.value.TJRL = sum;
  deptAllotForm.value.SZTJ = sumValues(deptAllotForm.value.groupNumInfo, 'num');
  console.log(item, deptAllotForm.value.groupNumInfo, deptAllotForm.value.SZTJ);
};
// 增加病例量-应用全部按钮点击
const handleApplyAll = () => {
  // deptAllotForm.value.YJZ = deptAllotForm.value.CSZ = Number(deptAllotForm.value.TJRL);
  deptAllotForm.value.groupNumInfo.forEach(item => {
    item.num = Number(deptAllotForm.value.TJRL);
  });
  // caseloadForm.value.YJZ = caseloadForm.value.CSZ = Number(caseloadForm.value.TJRL);
  deptAllotForm.value.SZTJ = sumValues(deptAllotForm.value.groupNumInfo, 'num');
};
// 表单提交按钮
/*
  type 0:增加研究者及机构
  type 1:分配结果
  type 2:增加病例量
  type 3:各分组病例量
  type 4:各中心病例量
*/
const deptAllSubmit = (form, done) => {
  let formVal = JSON.parse(JSON.stringify(form));
  delete formVal.hospitalDeptName;
  formVal.trial = routerQuery.value.trialId;
  if (deptMenuType.value === 0) {
    hospitalCaseNumSubmit(formVal).then(
      res => {
        ElMessage.success('操作成功!');
        initData();
        isDeptAllot.value = false;
        done();
      },
      error => {
        done();
      }
    );
  } else {
    formVal.groupNumInfo = JSON.stringify(formVal.groupNumInfo);
    formVal.trialId = routerQuery.value.trialId;
    addGroupCaseNum(formVal).then(
      res => {
        ElMessage.success('操作成功!');
        initData();
        isDeptAllot.value = false;
        done();
      },
      error => {
        done();
      }
    );
  }
};
const sumValues = (array, key = 'caseNum') => {
  return array.reduce((sum, item) => {
    return sum + Number(item[key]); // 将 value 转换为数字后累加
  }, 0); // 初始值为 0
};
// 接口方法
const initData = () => {
  // 各中心病例量
  hospitalCaseNumOfTrial(routerQuery.value.trialId || -1).then(res => {
    centreCaseList.value = res.data.data;
    centreCaseSum.value = sumValues(centreCaseList.value);
  });
  // 各分组病例量
  groupListOfTrial(routerQuery.value.trialId || -1).then(res => {
    groupCaseList.value = res.data.data;
    groupCaseSum.value = sumValues(groupCaseList.value);
  });
};
const initTrialDetail = id => {
  if (id) {
    getTrialDetail(id).then(res => {
      getTrialStatus.value = res.data.data.status;
    });
  }
};
onMounted(() => {
  initData();
  getTrialStatus.value = '2';
  initTrialDetail(routerQuery.value.trialId);
});
</script>
<style scoped>
.dept-allot-content {
  width: 70%;
  height: 100%;
}
.dept-header-btn {
  width: 100%;
  height: auto;
  margin-bottom: 10px;
}
.case-content {
  width: 100%;
  height: 660px;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
}
.group-case-content {
  width: 48%;
  height: 98%;
  display: flex;
  flex-direction: column;
  align-items: center;
  border: 1px solid #dddddd;
  overflow-y: auto;
}
.group-case-header {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  font-size: 14px;
  color: black;
  margin-bottom: 10px;
}
.group-case-list {
  width: 90%;
  height: 50px;
  color: #3c8dbc;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1px solid #dddddd;
  cursor: pointer;
}
.group-case-label {
  width: 68%;
  height: auto;
}
.group-case-value {
  width: 30%;
  height: auto;
}
</style>
